#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>

#include "AES.h"


#define MAX 1024
#define SERVER_HOST "localhost"
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 1234
struct sockaddr_in server_addr;
int sock, r;
int client_init()
{
    printf("======= clinet init ==========\n");
    printf("1 : create a TCP socket\n");
    sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        printf("socket call failed\n");
        exit(1);
    }
    printf("2 : fill server_addr with server’s IP and PORT\n");
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP); // localhost
    server_addr.sin_port = htons(SERVER_PORT);       // server port number
    printf("3 : connecting to server ....\n");
    r = connect(sock, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (r < 0)
    {
        printf("connect failed\n");
        exit(3);
    }
    printf("4 : connected OK to\n");
    printf("-------------------------------------------------------\n");
    printf("Server hostname=%s PORT=%d\n", SERVER_HOST, SERVER_PORT);
    printf("-------------------------------------------------------\n");
    printf("========= init done ==========\n");
}
int main()
{
    int n, nAESEncryptLen;
    char line[MAX], ans1[MAX], ans2[MAX], key[9] = "20191312", out[MAX], *enline = NULL, *deline = NULL;

    client_init();
    printf("******** processing loop *********\n");
    while (1)
    {
        printf("input a line : ");
        bzero(line, MAX);           // zero out line[ ]
        fgets(line, MAX, stdin);    // get a line from stdin
        line[strlen(line) - 1] = 0; // kill \n at end
        if (line[0] == 0)           // exit if NULL line
            exit(0);
        // Send line to server
        
        //加密
        nAESEncryptLen = aes_128_ecb_encrypt(line, key, out);
        enline = base64_encode(out, nAESEncryptLen);

        n = write(sock, enline, MAX);
        printf("client: wrote n=%d bytes; line=%s\n", n, enline);
        memset(enline,'\0',sizeof(enline));
        // Read a line from sock and show it
        n = read(sock, ans1, MAX);
        //n = read(sock, ans2, MAX);
        //解密
        enline = base64_decode(ans1, strlen(ans1));
        aes_128_ecb_decrypt(enline, key, ans2);
        memset(enline,'\0',sizeof(enline));
        printf("client: read n=%d bytes; recive : %s decrypt : %s\n", n, ans1, ans2);
        memset(ans1,'\0',sizeof(ans1));
        memset(ans2,'\0',sizeof(ans2));

    }
}